function $(Nid){
    return document.getElementById(Nid);
}

var num_vir = getdifficulty();
var dir = 2;
var speed = 10;
var crazy = 1;
//var directions = ['U','D','R','L'];
var range = 50;
var canvas = $("myCanvas");
var context = canvas.getContext("2d");
document.addEventListener("keydown", onkeydown);





var Plan = function (image, x, y, n) {
    this.image = image;
    this.x = x;
    this.y = y;
    this.originX = x;
    this.originY = y;
    this.width = image.width / n;
    this.height = image.height;
    this.isCaught = false;
    this.frm = 0;
    this.dis = 0;
    this.n = n;
    this.dir = 1;  
    
};


Plan.prototype.getCaught = function (bool) {
    this.isCaught = bool;
    if (bool == false) {
        this.originX = 0;
        this.originY = this.y;
    }
};
Plan.prototype.testPoint = function (x, y) {
    var betweenX = (x >= this.x) && (x <= this.x + this.width);
    var betweenY = (y >= this.y) && (y <= this.y + this.height);
    return betweenX && betweenY;
};
Plan.prototype.move = function(dire){
            if(dire == 'R'){  
               this.x+=speed;
               dir = 3;
               
               }else if(dire == 'L'){
                
               this.x-=speed;
               dir = 1;
               
               }else if(dire == 'D'){
               
                this.y+=speed;
                dir = 4;
               
               }else if(dire == 'U'){
                
                this.y-=speed;
                dir = 2;
               }
            if(this.x>canvas.width){
                this.x = 0
            }else if(this.x<0){
                this.x = canvas.width
            }
            if(this.y>canvas.height){
                this.y = 0
            }else if(this.y<0){
                this.y=canvas.height
            }
            
        }
//病毒的移动规则，随机wander+靠近主角
Plan.prototype.move2 = function(obj){
    if(this.x>obj.x&&this.dis>5) this.x-=crazy;
    if(this.x<obj.x&&this.dis>5) this.x+=crazy;
    if(this.y<obj.y&&this.dis>5) this.y+=crazy;
    if(this.y>obj.y&&this.dis>5) this.y-=crazy;
    this.y = this.y+Math.random()*2>>0;
    this.x = this.x +Math.random()*2>>0;
    this.y = this.y-Math.random()*2>>0;
    this.x = this.x -Math.random()*2>>0;
    if(this.x>canvas.width){
        this.x = 0
    }else if(this.x<0){
        this.x = canvas.width
    }
    if(this.y>canvas.height){
        this.y = 0
    }else if(this.y<0){
        this.y=canvas.height
    }
}



//病毒的绘制方法
Plan.prototype.draw = function (ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height, 0, 0, this.width, this.height);
    ctx.restore();
    
    this.x = this.originX + 20 * Math.sin(Math.PI / 100 * this.y);
    this.dis++;
    if (this.dis >= 10) {//10帧换图
        this.dis = 0;
        this.frm++;
        if (this.frm >= this.n) this.frm = 0;
    }
};
//主角绘制方法
Plan.prototype.draw2 = function (ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height, 0, 0, this.width,this.height);
    ctx.restore();
    this.dis++;
    if (this.dis >= 10) {//3帧换图
        this.dis = 0;
        this.frm++;
        if (this.frm >= this.n) this.frm = 0;
    }
};
//碰撞检测
//这里可以用四叉树改进，但考虑游戏规模不大，没有用
Plan.prototype.hitTestObject = function (planobj) {
    //if (this.x >= planobj.x	&& this.x <= planobj.x + planobj.width
    //		&& this.y >= planobj.y && this.y <= planobj.y - planobj.height
    //	)
    if(isColliding(this.x+5,this.y+5,this.width-20,this.height-20,
            planobj.x+5,planobj.y+5,planobj.width-20,planobj.height-20))
                 //发生碰撞 
        return true;
    else
        return false;

}

//基本的碰撞检验
function  isColliding( ax, ay, aw, ah,  bx,  by,  bw,  bh)
{ 
   if(ay > by + bh  || by > ay + ah 
       || ax > bx + bw || bx > ax + aw) 
     return false; 
   else
     return true; 
} 


//子弹类
var Bullet = function (image, x, y,object) {
    this.image = image;
    this.x = x;
    this.y = y;
    this.originX = x;
    this.originY = y;
    this.width = image.width/4;
    this.height = image.height;
    this.isCaught = false;
    this.frm = 0;
    this.dis = 0;
    this.object = object;

};
Bullet.prototype.testPoint = function (x, y) {
    var betweenX = (x >= this.x) && (x <= this.x + this.width);
    var betweenY = (y >= this.y) && (y <= this.y + this.height);
    return betweenX && betweenY;
};
Bullet.prototype.move = function () {
    switch(dir){
        case 1:
           this.x--;
           //console.log("GGOOG");
           break;           
        case 2:
            this.y--;  
            //console.log("RUNRUNRUN");
            break;         
       case 3:
           this.x++;
           break;
       case 4:
           this.y++;
           break;
    }

    if(this.x>canvas.width){
        this.x = 0
    }else if(this.x<0){
        this.x = canvas.width
    }
    if(this.y>canvas.height){
        this.y = 0
    }else if(this.y<0){
        this.y=canvas.height
    }
    
};


Bullet.prototype.draw = function (ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height, 0, 0, this.width, this.height);
    ctx.restore();
    this.move();
    
    this.dis++;
    if (this.dis >= 10) {//10帧换图
        this.dis = 0;
        this.frm++;
        if (this.frm >= 4) this.frm = 0;
    }
};	
Bullet.prototype.hitTestObject = function (planobj) {
    if(isColliding(this.x,this.y,this.width,this.height,
            planobj.x,planobj.y,planobj.width,planobj.height))//发生碰撞 
        return true;
    else
        return false;
}

Bullet.prototype.isFire=function(obj,ran){
    if(this.x>obj.x+ran||this.y>obj.y+ran
         ||this.y<obj.y-ran||this.x<obj.x-ran
       )
        return true;
    else{
        return false;
                        
    }
}   

//爆炸动画
var Bomb= function (image, x, y) {
    this.image = image;
    this.x = x;
    this.y = y;
    this.width = image.width/6;
    this.height = image.height ;
    this.frm = 0;
    this.dis = 0;
};

Bomb.prototype.draw2 = function (ctx) {
    ctx.save();
    ctx.translate(this.x, this.y);
    if (this.frm >= 6) return ;
    ctx.drawImage(this.image, this.frm *this.width, 0 , this.width, this.height, 0, 0, this.width, this.height);
    ctx.restore();     
    this.dis++;
    if (this.dis >= 10) {//10帧换图
        this.dis = 0;
        this.frm++;
        //if (this.frm >= 6) this.frm = 0;
    }
};		

var isClicked = false;

var mt = 0
var plans=[];
var bullets = [];
var bombs = [];
var cells = [];


var overflag=false;//游戏是否结束，true为结束
var player;
var image = new Image();
var image2 = new Image();
var image3 = new Image();
var image4 = new Image();
var image5 = new Image();
var image6 = new Image();
//var background = new Image();
//background.src = "bg.jpg";
image.src = "player.png";
image.onload = function () {

};
image2.src = "bomb.png";
image2.onload = function () {

};
image5.src = "cell.png";
image5.onload = function () {

};

image6.src = "tool.png";
image6.onload=function(){

}

image3.src = "virus.png";
image3.onload = function () {
    var ctx = $("information").getContext("2d");
    ctx.font = "40px jgl.TTF";
    ctx.fillText("尊敬的胶囊指挥官阁下，细胞等着您的救助",0,10)
    ctx.fillText("注意，您的特效子弹射程有限，可以通过获取道具增加射程，同时，",0,30)
    ctx.fillText("细胞和子弹都会跟随您行动，如果细胞遇到病毒，有概率造成细胞",0,50)
    ctx.fillText("死亡和病毒的分裂可能产生道具,如果细胞损失殆尽，病毒必变强。",0,70)


    player = new Plan(image, 300 * Math.random(), 400* Math.random(), 3);

    for(var i = 0 ; i<num_vir;i++){
        temX = Math.random()*480;
        temY = Math.random()*480;
        if(!isColliding(  player.x, player.y, player.width, player.height,  temX,  temY, 60,  60))
            plans.push(new Plan(image3, temX,temY, 3));
    } 
    
    for(var i = 0 ; i<10;i++){
        temX = Math.random()*480;
        temY = Math.random()*480;
        if(!isColliding(  player.x, player.y, player.width, player.height,  temX,  temY, 60,  60))
            cells.push(new Bullet(image5, temX,temY));
    } 

    var main = setInterval(function () {
        context.clearRect(0, 0, 320, 480);
        context.fillStyle = '#FFE4E1';
        context.fillRect( 0,0,480, 480);
        //画主角
        
        
        if(!overflag)//游戏没有结束
            player.draw2(context);//原地不动
        else{ 
            mt++;
            if(mt>=10){
                clearInterval(main);
            }
        }
        //画敌人
        for (var i = plans.length - 1; i >= 0; i--) {
            //var direction = Math.round(Math.random()*4);    
            plans[i].draw(context);
            plans[i].move2(player);
        }
        
        //画细胞
        for (var i = cells.length - 1; i >= 0; i--) {
            cells[i].draw(context);
        }

        //画子弹
        for (var i = bullets.length - 1; i >= 0; i--) {
            if (bullets[i].isFire(player,range))
                bullets.splice(i, 1); //删除子弹
            else
                bullets[i].draw(context,player);
        }


        //碰撞检测
        //判断病毒碰到玩家    
        for (var i = plans.length - 1; i >= 0; i--) {
            e1=plans[i];
            if (e1!=null && player!=null && player.hitTestObject(e1))
            {
               plans.splice(i, 1); //删除病毒				   
               bombs.push(new Bomb(image2, player.x, player.y));
               overflag=true;
               alert("病毒终将失败！")			   
            }
        }

        
        //判断子弹碰到病毒
        for (var j = bullets.length - 1; j >= 0; j--) {
            var b1=bullets[j];	
            for (var i = plans.length - 1; i >= 0; i--) {
                e1=plans[i];
                if (e1!=null && b1!=null && b1.hitTestObject(e1))//击中
                {
                   plans.splice(i, 1); //删除
                   bullets.splice(j, 1); //删除此颗子弹
                   bombs.push(new Bomb(image2, b1.x, b1.y));   
                   score+=1;
                }
        }
        var row = 90;
        //判断病毒碰到细胞
        for (var j = cells.length - 1; j >= 0; j--) {
            var c1=cells[j];		
            for (var i =plans.length - 1; i >= 0; i--) {
                e1=plans[i];
                if (e1!=null && c1!=null && c1.hitTestObject(e1))
                {
                   cells.splice(j, 1); 
                   plans.push(new Plan(image3, c1.x, c1.y,3));
                   bombs.push(new Bomb(image6, c1.x, c1.y));
                   console.log("divided"); 
                   ctx.fillText("病毒分裂！",0,row);
                   row +=20;
                   var s = Math.random();
                   if(s>0.5){
                        range = +50;speed+=1;ctx.fillText("细胞激发了您的战斗力！",0,row);row+=20;
                   }
                }          
                }
            }
        }

        //画炸弹
        for (var i = bombs.length - 1; i >= 0; i--) {
            if (bombs[i].frm >=6)
                bombs.splice(i, 1); //删除炸弹
            else
                bombs[i].draw2(context);
        }

        if(cells.length == 0){
            crazy = 10;
        }else if(plans.length==0){
            overflag =true ;
            alert("战胜病毒了！")
        }
        
    }, 1000 / 60);
};

image4.src = "bullet.png";//子弹图片
image4.onload = function () {

};

function onkeydown(e) {
    if (e.keyCode==32) {//空格
       //发射子弹
        //bullets.push(new Bullet(image4,300*Math.random(),420*Math.random()));		
        bullets.push(new Bullet(image4, player.x, player.y,player,player));//
    }else if (e.keyCode==37) {//向左
        player.move('L');
    }else if (e.keyCode==39) {//向右
        player.move('R');
    }else if (e.keyCode==38) {//向上
        player.move('U');
    }else if (e.keyCode==40) {//向下
        player.move('D');
    }
}
